package com.wyl.mq.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 吴宇亮 on 2023/6/9 15:44
 */
@Configuration
public class DelayQueueConfig {

    /**
     * 延迟队列：输入
     */
    public static final String delayQueue = "delayQueue";

    /**
     * 死信交换机
     */
    public static final String delayExchange = "delayExchange";

    @Bean
    public Queue delayQueue() {
        // return QueueBuilder.nonDurable(delayQueue).build();
        return new Queue(delayQueue);
    }

    /**
     * 旧版的rabbitmq delay插件会有一个bug，启动的时候不能自动创建延时交换机，如果延迟交换机不存在，则会启动报错
     * https://github.com/rabbitmq/rabbitmq-delayed-message-exchange/issues/19
     *
     * 解决方法：现在rabbitmq控制台手工创建该交换机即可
     */
    @Bean
    public CustomExchange delayExchange () {
        Map<String, Object> args = new HashMap<>();
        args.put("x-delayed-type", "topic");
        return new CustomExchange(delayExchange, "x-delayed-message", true, false);
    }

    @Bean
    public Binding delayQueueBinding(@Qualifier("delayQueue") Queue delayQueue,
                                         @Qualifier("delayExchange") Exchange delayExchange){
        return BindingBuilder.bind(delayQueue).to(delayExchange).with("*").noargs();
    }
}
